import createElement from './createElement.js'
import createDOMElement from './createDOMElement.js'
import patch from './patch.js'

export default class MyVue {
  constructor(options) {
    this.$options = options
    this.$data = options.data
    this.$el = options.el

    this._initData()

    // _ 表示私有属性，不想暴露到外部的
    this._vnode = this._render()
    createDOMElement(this._vnode)

    if (this.$el) {
      this.$mount(this.$el)
    }
  }

  $mount(el) {
    const container = document.querySelector(el)
    container.after(this._vnode.elm)
    container.remove()
  }

  _initData() {
    const _this = this
    const newProto = Object.create(Array.prototype)

    newProto.push = function (item) {
      console.log('监听到数组更新了')
      Array.prototype.push.call(this, item)
      _this._vnode = patch(_this._vnode, _this._render())
    }

    for (let [k, v] of Object.entries(this.$data)) {
      if (Array.isArray(v)) {
        v.__proto__ = newProto
      }

      Object.defineProperty(this, k, {
        get() {
          console.log('你想干啥...')
          return v
        },
        set: (newVal) => {
          v = newVal
          console.log('监听到有新数据来了，需要patch更新dom')

          console.log(this._vnode, 'oldVnode')
          console.log(this._render(), 'newVnode')

          this._vnode = patch(this._vnode, this._render())
        }
      })
    }
  }

  _render() {
    return this.$options.render.apply(this, [createElement])
  }
}

// new MyVue({
//   // el: '#app',
//   data: {
//     msg: 'hehe'
//   },
//   methods: {},
//   render(h) {
//     return h('div', { attrs: { id: 'app' } }, ['hehedat'])
//   }
// }).$mount('#app')
